﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Drawing.Imaging;
using System.Drawing;
using System.Text;
using SqlSugar;
using Models;
using Commonality.Common;
using System.Security.Claims;
using AutoMapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using IService.Managemen;
using ModelToDto.Managemen;

namespace ManagementPlatform.Controllers
{
    public class HomeController : Controller
    {
        IUserService _userService;
        IMapper _mapper;
        public HomeController(IUserService userService, IMapper mapper) { this._userService = userService; this._mapper = mapper; }
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "PlatAuthoriPloicy")]
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 登录界面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login() { return View(); }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<FileResult> VerifyCode()
        {
            string code = String.Empty;
            Bitmap bitmap = Common.CreateVerifyCode(out code);
            base.HttpContext.Session.SetString("CheckCode", code);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            return await Task.FromResult<FileResult>(File(stream.ToArray(), "image/gif"));
        }
        /// <summary>
        /// 提交登录验证
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login([FromForm] LoginUserDTO loginUserDTO)
        {
            var viCode = base.HttpContext.Session.GetString("CheckCode")?.ToLower();
            if (loginUserDTO.CheckCode == viCode)
            {
                var userEnt = _userService.LoginUser(loginUserDTO);
                if (userEnt != null)
                {
                  

                    ClaimsIdentity claimsIdentity = new ClaimsIdentity("userclaim");//这里必须给定一个类型名称，否则在上下文中获取不到claim
                    claimsIdentity.AddClaim(new Claim("Name", userEnt?.Name));
                    claimsIdentity.AddClaim(new Claim("Pwd", userEnt?.Password));
                    claimsIdentity.AddClaim(new Claim("Uid", userEnt?.UserId.ToString()));
                    ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
                    var authProperties = new AuthenticationProperties
                    {
                        //AllowRefresh = <bool>,
                        // Refreshing the authentication session should be allowed.

                        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
                        // The time at which the authentication ticket expires. A 
                        // value set here overrides the ExpireTimeSpan option of 
                        // CookieAuthenticationOptions set with AddCookie.

                        //IsPersistent = true,
                        // Whether the authentication session is persisted across 
                        // multiple requests. When used with cookies, controls
                        // whether the cookie's lifetime is absolute (matching the
                        // lifetime of the authentication ticket) or session-based.

                        //IssuedUtc = <DateTimeOffset>,
                        // The time at which the authentication ticket was issued.

                        //RedirectUri = <string>
                        // The full path or absolute URI to be used as an http 
                        // redirect response value.
                    };
                    var result= HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            principal,
            authProperties);
                    return  Redirect("/Home/Index");
                }

            }
         return View(loginUserDTO);
        }
    }
}
